package net.lastcoder.ifserver.nio;

import net.lastcoder.ifserver.Server;
import net.lastcoder.ifserver.packet.PacketParser;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * auth: WenYF
 * date: 2016/10/8
 */
public class PacketDecoder extends CumulativeProtocolDecoder {
    @Override
    protected boolean doDecode(IoSession session, IoBuffer in
            , ProtocolDecoderOutput out) throws Exception {
        PacketParser packetParser = (PacketParser) session
                .getAttribute(ConnectionHandler.PACKET_PARSER);
        if (in.hasRemaining()) {
            int len = in.remaining();
            
            Server.inConnCount += len;
            Server.inCount += len;
            
            packetParser.read(in);
            while (packetParser.hasPacket()) {
                out.write(packetParser.getPacket());
            }
            return true;
        } else {
            return false;
        }
    }
}
